package com.hutao.manage.service.impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hutao.manage.mapper.InterfaceAdmIdInHosMapper;
import com.hutao.manage.mapper.MrTransfusionObservationMapper;
import com.hutao.manage.pojo.InterfaceAdmIdInHos;
import com.hutao.manage.pojo.MrTransfusionObservation;
import com.hutao.manage.service.SyncHisDataService;
import com.hutao.manage.util.CacheJdbcUtil;
import com.hutao.manage.util.DateUtil;

@Service
public class SyncHisDataServiceImpl implements SyncHisDataService {
	
	  private Logger logger = LoggerFactory.getLogger(SyncHisDataServiceImpl.class);

	    @Autowired
	    private InterfaceAdmIdInHosMapper interfaceAdmIdInHosMapper;
	    
	    @Autowired
	    private MrTransfusionObservationMapper mrTransfusionObservationMapper;

	    @Transactional
	    @Override
	    public String syncHisInterfaceAdmInHosInfo(String startDate,String endDate) {
	        PreparedStatement ps = null;
	        Connection con = null;
	        ResultSet rs = null;
	        try{
	            con = CacheJdbcUtil.getConn();
	        }catch(Exception e){
	            e.printStackTrace();
	            logger.error("连接his的InterSystems Caché 数据库失败!失败原因:"+e.getMessage());
	        }

	        CallableStatement cs = null;
	        List<InterfaceAdmIdInHos> interfaceAdmIdInHosList = new ArrayList<>();
	        try{
	            cs = con.prepareCall("{call web.DHCHisToOther_InAdmPatientInfoNew(?,?)}");
	            //给存储过程的参数设置值
	            cs.setString(1, startDate);
	            cs.setString(2, endDate);
	            rs = cs.executeQuery();
	            InterfaceAdmIdInHos interfaceAdmIdInHos = null;
	            while (rs.next()) {
	                interfaceAdmIdInHos = new InterfaceAdmIdInHos();
	                String patientId = rs.getString("ADMID");// HIS内部标识/PatientId
	                String patId = rs.getString("PATID");
	                String name = rs.getString("NAME");
	                String patNo = rs.getString("PATNO");
	                String mrId = rs.getString("MEDNO");
	                String onlyId = rs.getString("IPNo");
	                String disDate = rs.getString("DISDATE");
	                String bedDesc = rs.getString("BEDDESC");

	                interfaceAdmIdInHos.setMedicalClass("3");
	                interfaceAdmIdInHos.setOrganization("山东省立医院");
	                interfaceAdmIdInHos.setOrganizationId("49557184-0");
	                interfaceAdmIdInHos.setMrId(StringUtils.isEmpty(mrId)?null:mrId);
	                interfaceAdmIdInHos.setName(StringUtils.isEmpty(name)?null:name);
	                interfaceAdmIdInHos.setOnlyId(StringUtils.isEmpty(onlyId)?null:onlyId);
	                interfaceAdmIdInHos.setPatId(StringUtils.isEmpty(patId)?null:patId);
	                interfaceAdmIdInHos.setPatientId(StringUtils.isEmpty(patientId)?null:patientId);
	                interfaceAdmIdInHos.setPatNo(StringUtils.isEmpty(patNo)?null:patNo);
	                interfaceAdmIdInHos.setInTime(null);
	                interfaceAdmIdInHos.setBedDesc(StringUtils.isEmpty(bedDesc)?null:bedDesc);
	                interfaceAdmIdInHosList.add(interfaceAdmIdInHos);
	            }
	            logger.info("存储过程执行：call web.DHCHisToOther_InAdmPatientInfoNew("+startDate+","+endDate+")成功!");

	        }catch(Exception e){
	            e.printStackTrace();
	            logger.error("存储过程执行：call web.DHCHisToOther_InAdmPatientInfoNew("+startDate+","+endDate+")失败!失败原因:"+e.getMessage());
	        }finally {
		        //关闭InterSystems Caché数据库连接
		        try{
		            if(rs!=null) rs.close();
		            if(ps!=null)ps.close();
		            if(con!=null)con.close();
		            logger.info("关闭InterSystems Caché数据库连接成功!");
		        }catch(Exception e){
		            e.printStackTrace();
		            logger.error("关闭InterSystems Caché数据库连接失败，失败原因:"+e.getMessage());
		        }
	        }
	        logger.info("执行存储过程:call web.DHCHisToOther_InAdmPatientInfoNew("+startDate+","+endDate+")查询出数据条数为:"+interfaceAdmIdInHosList.size());
	        if(CollectionUtils.isEmpty(interfaceAdmIdInHosList)){
	            return "执行存储过程:call web.DHCHisToOther_InAdmPatientInfoNew("+startDate+","+endDate+")存储过程执行成功,查询数据为空!";
	        }
	       
	        int addCount = 0;
	        int updateCount = 0;
	        
	        for (InterfaceAdmIdInHos interfaceAdmIdInHos : interfaceAdmIdInHosList) {
				String patientId = interfaceAdmIdInHos.getPatientId();
				
				//根据his的patientId判断是否存在,存在更新床号，不存在新增
				List<InterfaceAdmIdInHos> oldInterfaceAdmIdInHosList = interfaceAdmIdInHosMapper.getInterfaceAdmInHosByPatientId(patientId);
				if(CollectionUtils.isNotEmpty(oldInterfaceAdmIdInHosList)) {
					for (InterfaceAdmIdInHos oldinterfaceAdmIdInHos : oldInterfaceAdmIdInHosList) {
						oldinterfaceAdmIdInHos.setBedDesc(interfaceAdmIdInHos.getBedDesc());
						interfaceAdmIdInHosMapper.updateByPrimaryKeySelective(oldinterfaceAdmIdInHos);
					}
					updateCount++;
				}else {
					interfaceAdmIdInHosMapper.insertSelective(interfaceAdmIdInHos);
					addCount++;
				}   	
			}
	        
	        logger.info("同步患者入院信息interfaceAdmIdInHos,新增:"+addCount+"条,更新:"+updateCount+"条");

	        return "同步患者入院信息interfaceAdmIdInHos,新增:"+addCount+"条,更新:"+updateCount+"条";

	    }

	    @Transactional
		@Override
		public String syncHisApplyReportQryPack(String startDate, String endDate) {
	    	
	    	 PreparedStatement ps = null;
		     Connection con = null;
		     ResultSet rs = null;
		     try{
		         con = CacheJdbcUtil.getConn();
		     }catch(Exception e){
		         e.printStackTrace();
		         logger.error("连接his的InterSystems Caché 数据库失败!失败原因:"+e.getMessage());
		     }
		     CallableStatement cs = null;
		     int totalCount = 0;
		     int clinicCount = 0;
		     int zyCount = 0;
		     int repeatCount = 0;
		     int addCount = 0;
		      try{
		         cs = con.prepareCall("{call LIS_Service_BldUpLoad_CS_SDSL.ApplyReport_QryBldInfo(?,?)}");
		         //给存储过程的参数设置值
		         cs.setString(1, startDate);
			     cs.setString(2, endDate);
		         rs = cs.executeQuery();
			     MrTransfusionObservation mrTransfusionObservation = null;
		         while (rs.next()) {
		        	 	totalCount++;
		        		//patientId+"--"+PATNAME+"--"+mrId+"-"+REQUESTID+"--"+APPLY_TYPE+"--"+PURPOSES+"--"+EXAMINE_TIME+"--"+BLOODBAG+"--"+COMPONENT+"--"+COMPONENT_AMOUNT);
		            	//19771810--孙小然--6543235-202001010190--常规治疗--补充凝血因子--2020-01-02 18:09:40--=0160119203723||=<P0065VA0 1--悬浮去白红细胞--0.50 
		            	mrTransfusionObservation = new MrTransfusionObservation();
						String patientId = rs.getString("就诊号");
			        	String mrId = rs.getString("住院号");
			        	// 排除非住院数据
			        	if(StringUtils.isEmpty(mrId)) {
			        		clinicCount++;
			        		continue;
			        	}
			        	
			        	zyCount++;
			        	
						String PATNAME = rs.getString("病人姓名");
						String REQUESTID = rs.getString("申请单号");
						String APPLY_TYPE = rs.getString("申请单类型");
						String PURPOSES = rs.getString("申请目的");
						
						String EXAMINE_TIME = rs.getString("接收时间");
						String BLOODBAG = rs.getString("血袋编码");
						String COMPONENT = rs.getString("血制品");
						String COMPONENT_AMOUNT = rs.getString("数量");
						
						//去除已有数据
						if(StringUtils.isNotBlank(REQUESTID) && StringUtils.isNotBlank(BLOODBAG)) {
							int bloodCount = mrTransfusionObservationMapper.getObservationCount(REQUESTID,BLOODBAG);
							if(bloodCount>0) {
								repeatCount++;
								continue;
							}
						}
						
						
						mrTransfusionObservation.setMedicalClass("3");
						mrTransfusionObservation.setMrId(mrId);
						mrTransfusionObservation.setOrganizationId("49557184-0");
						mrTransfusionObservation.setOrganization("山东省立医院");
						mrTransfusionObservation.setBranchId("1");
						mrTransfusionObservation.setSerialNumber(mrTransfusionObservationMapper.getSerialNumberByPatientId(patientId));
						mrTransfusionObservation.setOnlyId(mrTransfusionObservationMapper.getOnlyIdByPatientId(patientId));
						mrTransfusionObservation.setName(PATNAME);
						mrTransfusionObservation.setCollectionTime(DateUtil.dateParse("yyyy-MM-dd HH:mm:ss", EXAMINE_TIME));
						mrTransfusionObservation.setComponent(COMPONENT);
						mrTransfusionObservation.setComponentAmount(Double.valueOf(COMPONENT_AMOUNT));
						mrTransfusionObservation.setApplyNo(REQUESTID);
						mrTransfusionObservation.setBloodBag(BLOODBAG);
						mrTransfusionObservation.setApplyType(APPLY_TYPE);
						mrTransfusionObservation.setPurposes(PURPOSES);
						mrTransfusionObservation.setRecordTime(new Date());
						
						mrTransfusionObservationMapper.insertSelective(mrTransfusionObservation);
						addCount++;
						
		            }
		            logger.info("存储过程执行：call LIS_Service_BldUpLoad_CS_SDSL.ApplyReport_QryBldInfo("+startDate+", "+endDate+")成功!");

		        }catch(Exception e){
		            e.printStackTrace();
		            logger.error("存储过程执行:call LIS_Service_BldUpLoad_CS_SDSL.ApplyReport_QryBldInfo("+startDate+", "+endDate+")失败!失败原因:"+e.getMessage());
		        }finally {
			        //关闭InterSystems Caché数据库连接
			        try{
			            if(rs!=null) rs.close();
			            if(ps!=null)ps.close();
			            if(con!=null)con.close();
			            logger.info("关闭InterSystems Caché数据库连接成功!");
			        }catch(Exception e){
			            e.printStackTrace();
			            logger.error("关闭InterSystems Caché数据库连接失败，失败原因:"+e.getMessage());
			        }
		        }
		        logger.info("同步"+startDate+"-"+endDate+"输血数据:his数据条数为:"+totalCount+",his门诊数据"+clinicCount+"条,his住院数据"+zyCount+"条,系统已存在"+repeatCount+"条,新增输血"+addCount+"条");
		      
	    	
	    	
	    	return "同步"+startDate+"-"+endDate+"输血数据:his数据条数为:"+totalCount+",his门诊数据"+clinicCount+"条,his住院数据"+zyCount+"条,系统已存在"+repeatCount+"条,新增输血"+addCount+"条";
	    	
		}

	    @Transactional
		@Override
		public String syncOpApplyBedInfo() {
	    	
	    	List<Map<String,Object>> list = interfaceAdmIdInHosMapper.getOpApplyBedDesc();
	    	if(CollectionUtils.isEmpty(list)) {
	    		return "查询数据为空!";
	    	}
	    	StringBuilder builder = new StringBuilder();
	    	int updateCount = 0;
	    	for (Map<String, Object> map : list) {
	    		Long id = MapUtils.getLong(map, "ID");
	    		String bedDesc = MapUtils.getString(map, "bed_desc".toUpperCase());
	    		if(StringUtils.isEmpty(bedDesc)) {
	    			continue;
	    		}
	    		
	    		interfaceAdmIdInHosMapper.updateOpApplyBedById(id, bedDesc);
	    		updateCount++;
	    		
	
			}
	    	builder.append("查询出床位总数:"+list.size());
	    	builder.append("更新床位总数为:"+updateCount);
	    	
	    	try {
				logger.info(DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", new Date())+"更新手术申请排班床位信息:"+builder.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
			return builder.toString();
		}
	    
	    
	  
	
}
